<template>
  <view class="withdraw-records-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <uni-icons 
        type="arrowleft" 
        size="24" 
        color="#333" 
        @click="goBack"
      ></uni-icons>
      <text class="nav-title">提现记录</text>
      <view class="nav-right"></view>
    </view>
    
    <!-- 筛选栏 -->
    <view class="filter-bar">
      <picker 
        class="filter-item" 
        mode="selector" 
        :range="statusOptions" 
        range-key="label"
        :value="filterStatusIndex" 
        @change="onStatusChange"
      >
        <view class="filter-content">
          <text>{{ statusOptions[filterStatusIndex].label }}</text>
          <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
        </view>
      </picker>
      
      <picker 
        class="filter-item" 
        mode="date" 
        fields="month" 
        :value="filterDate" 
        @change="onDateChange"
      >
        <view class="filter-content">
          <text>{{ filterDateText }}</text>
          <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
        </view>
      </picker>
    </view>
    
    <!-- 记录列表 -->
    <scroll-view 
      class="records-scroll" 
      scroll-y
      @scrolltolower="loadMore"
      :scroll-with-animation="true"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 统计信息 -->
      <view class="stats-card" v-if="filterStatusIndex === 0">
        <view class="stats-item">
          <text class="stats-label">成功提现</text>
          <text class="stats-value">¥{{ stats.successAmount }}</text>
        </view>
        <view class="stats-item">
          <text class="stats-label">提现次数</text>
          <text class="stats-value">{{ stats.successCount }}次</text>
        </view>
        <view class="stats-item">
          <text class="stats-label">总手续费</text>
          <text class="stats-value">¥{{ stats.totalFee }}</text>
        </view>
      </view>
      
      <!-- 记录列表 -->
      <view class="records-list">
        <withdraw-record-item 
          v-for="(record, index) in records" 
          :key="index" 
          :record="record" 
          @click="viewDetail(record)"
        />
        
        <!-- 加载状态 -->
        <view class="load-status">
          <uni-load-more 
            :status="loadStatus" 
            :content-text="{
              contentdown: '上拉加载更多',
              contentrefresh: '加载中',
              contentnomore: '没有更多了'
            }" 
          />
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="records.length === 0 && !loading">
          <image 
            class="empty-image" 
            src="/static/images/empty-withdraw.png" 
            mode="aspectFit"
          ></image>
          <text class="empty-text">暂无提现记录</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import WithdrawRecordItem from './components/WithdrawRecordItem.vue'

// 筛选状态选项
const statusOptions = ref([
  { label: '全部状态', value: 'all' },
  { label: '处理中', value: 'processing' },
  { label: '成功', value: 'success' },
  { label: '失败', value: 'failed' }
])

// 统计信息
const stats = ref({
  successAmount: '5,256.80',
  successCount: 12,
  totalFee: '78.85'
})

// 记录数据
const records = ref([])
const page = ref(1)
const pageSize = 15
const loadStatus = ref('more') // more / loading / noMore
const refreshing = ref(false)

// 筛选条件
const filterStatusIndex = ref(0)
const filterDate = ref('')
const filterDateText = computed(() => {
  if (!filterDate.value) return '全部时间'
  const date = new Date(filterDate.value)
  return `${date.getFullYear()}年${date.getMonth() + 1}月`
})

// 页面加载
onLoad(() => {
  // 获取当前月份作为默认筛选
  const now = new Date()
  filterDate.value = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`
  // 获取初始数据
  fetchRecords()
})

// 获取记录数据
const fetchRecords = (refresh = false) => {
  if (loadStatus.value === 'noMore' && !refresh) return
  
  if (refresh) {
    page.value = 1
    refreshing.value = true
  } else {
    loadStatus.value = 'loading'
  }
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 模拟数据
    const newData = generateMockRecords(
      page.value, 
      pageSize, 
      statusOptions.value[filterStatusIndex.value].value,
      filterDate.value
    )
    
    if (newData.length === 0) {
      loadStatus.value = 'noMore'
      if (page.value === 1) {
        records.value = []
      }
    } else {
      records.value = refresh ? newData : [...records.value, ...newData]
      page.value++
      loadStatus.value = newData.length < pageSize ? 'noMore' : 'more'
    }
    
    if (refresh) {
      refreshing.value = false
    }
  }, 800)
}

// 生成模拟记录数据
const generateMockRecords = (page, size, status, dateFilter) => {
  if (page > 3) return [] // 模拟只有3页数据
  
  const statusTypes = ['processing', 'success', 'failed']
  const methods = ['alipay', 'bank']
  const methodNames = {
    'alipay': '支付宝',
    'bank': '银行卡'
  }
  
  let baseDate = new Date()
  if (dateFilter) {
    const [year, month] = dateFilter.split('-')
    baseDate = new Date(year, month - 1, 1)
  }
  
  const data = []
  for (let i = 0; i < size; i++) {
    // 如果筛选了状态，则只生成对应状态的记录
    const recordStatus = status === 'all' 
      ? statusTypes[Math.floor(Math.random() * statusTypes.length)]
      : status
    
    const amount = (100 + Math.random() * 4900).toFixed(2)
    const feeRate = recordStatus === 'success' ? (Math.random() > 0.5 ? 0.01 : 0.015) : 0
    const fee = (amount * feeRate).toFixed(2)
    const method = methods[Math.floor(Math.random() * methods.length)]
    
    const date = new Date(baseDate)
    date.setDate(Math.floor(Math.random() * 28) + 1)
    date.setHours(Math.floor(Math.random() * 24))
    date.setMinutes(Math.floor(Math.random() * 60))
    
    data.push({
      id: `withdraw_${page}_${i}`,
      amount,
      fee,
      actualAmount: (amount - fee).toFixed(2),
      method,
      methodName: methodNames[method],
      status: recordStatus,
      createTime: date.toISOString(),
      finishTime: recordStatus !== 'processing' ? new Date(date.getTime() + Math.random() * 3 * 24 * 60 * 60 * 1000).toISOString() : '',
      remark: recordStatus === 'failed' ? '银行卡信息有误' : ''
    })
  }
  
  // 按时间降序排序
  return data.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
}

// 状态筛选变化
const onStatusChange = (e) => {
  filterStatusIndex.value = e.detail.value
  // 重置分页数据
  page.value = 1
  records.value = []
  loadStatus.value = 'more'
  // 重新加载数据
  fetchRecords()
}

// 日期筛选变化
const onDateChange = (e) => {
  filterDate.value = e.detail.value
  // 重置分页数据
  page.value = 1
  records.value = []
  loadStatus.value = 'more'
  // 重新加载数据
  fetchRecords()
}

// 加载更多
const loadMore = () => {
  fetchRecords()
}

// 下拉刷新
const onRefresh = () => {
  fetchRecords(true)
}

// 查看详情
const viewDetail = (record) => {
  uni.navigateTo({
    url: `/pages/wallet/withdraw-detail?id=${record.id}`
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>

.withdraw-records-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $light-bg;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: $white-bg;
  border-bottom: 1rpx solid #f5f5f5;
  
  .nav-title {
    font-size: $font-size-32rpx;
    font-weight: bold;
    color: $text-color;
  }
  
  .nav-right {
    width: 24px;
  }
}

.filter-bar {
  display: flex;
  padding: 20rpx 30rpx;
  background-color: $white-bg;
  border-bottom: 1rpx solid #f5f5f5;
  
  .filter-item {
    flex: 1;
    margin: 0 10rpx;
    
    .filter-content {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: $font-size-26rpx;
      color: $text-color;
      background-color: $light-bg;
      border-radius: 40rpx;
      padding: 12rpx 0;
      
      text {
        margin-right: 8rpx;
      }
    }
  }
}

.records-scroll {
  flex: 1;
  height: calc(100vh - 220rpx);
}

.stats-card {
  display: flex;
  background-color: $white-bg;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 30rpx;
  
  .stats-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .stats-label {
      font-size: $font-size-24rpx;
      color: $text-color-666;
      margin-bottom: 15rpx;
    }
    
    .stats-value {
      font-size: $font-size-28rpx;
      color: $text-color;
      font-weight: bold;
    }
  }
}

.records-list {
  background-color: $white-bg;
  border-radius: 16rpx;
  margin: 20rpx;
  min-height: 200rpx;
}

.load-status {
  padding: 30rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: $font-size-28rpx;
    color: $text-color-666;
  }
}
</style>